<?php require_once '../yubiphpbase/appinclude.php';
require_once '../yubiphpbase/yubi_lib.php';

if ($argc != 2) {
        echo "\nImport shipping records into Yubico database:\n";
        echo "% php import_buyers shipping_record.csv\n";
        exit;
}

$fname = $argv[1];
if (! ($in = fopen($fname, "r"))) {
     echo 'Cannot open file '.$fname."\n";
     exit(1);
}

// If run from the web
//header("content-type: text/plain");
//$fname = '/yubico/OrderRecords_20080929.csv';
//echo "\nImport shipping records into Yubico database:\n";
//echo "% php import_buyers shipping_record.csv\n";

if (! ($in = fopen($fname, "r"))) {
     echo 'Cannot open file '.$fname."\n";
     exit(1);
}

$clientsAdded = $rowN = $buyersAdded = $keysIssued = 0;
//$pat = '/(\w+@\w+)/';
$pat = '/(\([\w|\.]+@[\w|\.]+\))/';
$client = 0;

while (($line = fgets($in, 1024)) !== FALSE) {
	$rowN++;
	
	if (trim($line) == '') {
//		echo 'Skip empty row '.$rowN."\n";
		continue;
	}

	if (($x=strpos($line, '@')) !== false) { // A name (email) line
		$email = trim(strAfter($line, '('));
		$n = strpos($email, ')');
		$email = substr($email, 0, $n);
		
		$name = trim(strBefore($line, '('));
		echo '* Email='.$email.', Name='.$name."\n";				
			
		//// Srch client by email
		//
		if (($client=getClientByEmail($email)) <= 1) { 
			// No client owner of the key, add a new client
			if (($client = addClient($email, genAPIKey(), 3,
				'Imported by shipping records before 6/4/08')) > 1) {
			  		$clientsAdded++;
			  		echo 'New client added: '.$email;
			} else {
				echo ' failed adding client: '.$line."\n";
				continue;	
			}
		}

		if (getBuyerByClient($client) <= 0) {
			addBuyer($client, $name, '', $email, 0);
			$buyersAdded++;
		}
	} else { // Should be an OTP line
		if (strlen($line) > 32) { // OTP line
			echo '  OTP: '.$line."\n";
			// Add the yubikey to the client
			$devid = strtolower(substr($line, 0, 12));
			$ki = getKeyInfo($devid);
			if (!isset($ki['keyid'])) {
				echo $devid.' failed! non-exists key in DB in row '.$rowN."\n";
    			continue;
			}
			
			$keyid = $ki['keyid'];
			echo '> Client = '.$client.', keyId = '.$keyid."\n";
			//print_r($ki);
			if ($client > 1) {
				if ($ki['client'] <= 1) {	// A new key
					echo "! This is a new key, assign to client-".$client."\n";
					if (updClientOfKey($keyid, $client)) {
						$keysIssued++;
						echo 'Assign key '.$devid.' to client '.$client."\n";
					} else {
						echo 'X failed to assign key to client '.$client."\n";
					}
				} else if ($client != $ki['client']) { // Key ownership conflict
					echo 'Warning! '.$devid.' is owned by client '.$ki['client'].
						' in row '.$rowN."\n";
					continue;
				} else {
					//echo 'Key '.$devid.' already assigned to client '.$client."\n";					
				}				
			}
		} else {
			echo 'X Skip failed line: '.$line."\n";
			continue;
		}
	}
    
    echo "\n\n";

} // End of while each line

fclose($in);


function getBuyerByClient($client) {
	$stmt = 'SELECT id FROM buyers WHERE client_id='.$client;
	if ($r = query($stmt)) {
		if (($row = mysql_fetch_assoc($r))) {
			mysql_free_result($r);		
			return $row['id'];
		}
	}
	return -1;
}

function addBuyer($client, $name, $addr, $email, $qty) {
	$stmt = 'INSERT INTO buyers (name,email,addr,qty,client_id,created) VALUES ('.
		mysql_quote(truncate($name,45)).','.
		mysql_quote(truncate($email,100)).','.
		mysql_quote(truncate($addr,200)).','.
		$qty.','.
		$client.','.
		'NOW())';
	if (query($stmt)) {
		return mysql_insert_id();	
	}
	return -1;
} // End addBuyer
?>
